const { isJSRequest } = require('../../utils.js');
const send = require('../send.js');
const transformRequest = require('../transformRequest.js');
const { parse } = require('url');

// 判断如果请求的是 JS 文件的请就进行 JS 内容转换
function transformMiddleware(server) {
  return async function (req, res, next) {
    if (req.method !== 'GET') {
      return next();
    }
    let url = parse(req.url).pathname;
    const excludeUrls = ['/.well-known/appspecific/com.chrome.devtools.json'];
    if (isJSRequest(url) && !excludeUrls.includes(url)) {
      //切记这个地方要把req.url传给transformRequest，不是url,否则会丢失query
      const result = await transformRequest(req.url, server);
      if (result) {
        // .vue 文件内容响应头会设置为 application/javascript
        const type = 'js';
        return send(req, res, result.code, type); //返回的内容又会 request 请求 import 的文件
      }
      return next();
    } else {
      return next();
    }
  };
}
module.exports = transformMiddleware;
